package Tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Classname JZ55
 * @Description TODO
 * @Date 2023/2/23 16:25
 * @Created by xjl
 */
public class JZ55二叉树的深度 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public int maxDepth(TreeNode root) {
        if (root==null){
            return 0;
        }
        return deep(root);
    }

    private int deep(TreeNode root) {
        if (root==null){
            return 0;
        }
        int left=deep(root.left);
        int right=deep(root.right);
        return Math.max(left,right)+1;
    }


    public int maxDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        // 加入root节点
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            // 将每一层的队列的值都弹出即为深度数
            ans++;
        }
        return ans;
    }
}
